define([
    'Util',
    'list',
    'dialog',
    'select',
    'text!tpl/weekly/editWeekly.tpl',
    'text!tpl/weekly/editWeeklyTable.tpl',
    'text!tpl/weekly/editTable.tpl',
    'tab',
    'validator',
    'cookie',
    '../common/getPath',
    'form',
    'clipboard',
    '../common/getQueryString',
    '../common/dateFormat'
], function(Util, List, Dialog, Select, editWeeklyTpl,editWeeklyTable,editTable, Tab,Validator, $cookie, AjaxPath, Form, Clipboard, getQueryString) {
    require(['style!css/style.css']);
    var $el=null;
    var _indexModule = null,
        editWeeklyTab = null,
        editWeeklyValidation = null,
        getResult = null,
        getBean = null,
        weekDayAll = null,
        weekTimeAll = null,
        ContentAll = null,
        longTimeAll = null,
        remarksAll = null,
        editOption = null;

    var initialize = function(indexModule, options, tabItem){
        $el = $(editWeeklyTpl);
        _indexModule = indexModule;

        // 事件--点击切换tab后事件回调
        $(tabItem).on("tabActive", function() {
            tabItem.show(true); // 刷新表单
        });
        //console.log(viewRequirementData)
        editWeeklyTab = tabItem;
        this.content=$el;
        editOption = options;
        //console.log(editOption);
        // 业务相关代码
        editValidation();
        getWeekly();
        eventInit();
    };
    /*复制粘贴*/

    //按钮事件
    var eventInit = function (){
        //页面除dialog按钮功能
        $el.on('click', '.saveBtn', function () {
            if(editOption.id===null){
                editWeekly("keepWeek")
            }else{
                editWeekly("keepingWeek")
            }
        });//提交
        $el.on('click', '.submitBtn', function () {
            new Dialog({
                mode: 'confirm', // 对话框模式，默认normal标准|confirm浮动层|confirm确认对话框
                title: '提示',
                width: 300, //对话框宽度，可选项。normal默认值为600，confirm默认值为300，tips默认值为240
                height: 120, //对话框高度，可选项。normal默认值为400，confirm默认值为180，tips默认值为80
                cancelDisplay: true, //是否显示取消按钮（强制执行，可在confirm模式下生效），可选项。 默认true(显示)
                ok: function() {
                    if(editOption.id===null){
                        editWeekly("toSubmitWeek")
                    }else{
                        editWeekly("submitWeek")
                    }
                }, // 点击确定按钮的回调函数，可为空。如果指定 return false 则执行完方法后不关闭弹窗，默认 return true。若不配置该项，则不会出现确定按钮。
                okValue: '确定', //确定按钮的文本 默认是 ‘ok’
                modal: true,
                content: '<div style="text-align:center;margin-top:50px">' +'提交后将无法再次编辑，是否提交？'+'</div>'// 对话框内容，可以是字符串、html片段、或dom对象,默认为loading状态（点组成的圈）
            });


        });//保存
        $el.on('click', '.backBtn', btnBack);//返回


    };
    var htWeekDays = function(timestamp){//时间戳
        var weekDays = [];
        d =new Date((timestamp-0));
        nowYear = d.getYear();
        nowYear += (nowYear < 2000) ? 1900 : 0;
        w = d.getDay();
        n = (w == 0 ? 7 : w) - 1;
        d.setDate(d.getDate() - n);
        for(i=0; i<7; i++) {
            var dates = nowYear + '-' + (d.getMonth()+1) + '-' + d.getDate();
            weekDays.push(timeStamp(dates));
            d.setDate(d.getDate() + 1);
        }
        return weekDays
    };

    //时间戳转换成时间
    var timeStamp = function(timestamp){
        var timestampint = 0;
        if(!isNaN(timestamp)){
            timestampint = timestamp
        }else{
            var oodate = timestamp.replace("-", "/").replace("-", "/");
            timestampint = new Date(oodate)
        }
        var date = new Date(timestampint);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
        //var date = new Date(timestamp * 1000);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
        Y = date.getFullYear() + '-';
        M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
        D = (date.getDate() < 10 ? '0'+date.getDate() : date.getDate()) + ' ';
        h = date.getHours() + ':';
        m = date.getMinutes() + ':';
        s = date.getSeconds();
        return Y+M+D;
    }

    var btnBack = function() {
        editWeeklyTab.switchTab(editOption.menuId);
        editWeeklyTab.destroy("editWeek");
        require(['js/weekly/weeklyList'], function(weeklyList) {
            var result = new weeklyList({}, {}, editWeeklyTab);
            editWeeklyTab.content(result.content);
        });
        $(".ui-popup-backdrop, .ui-popup,.ui-popup-modal,.ui-popup-show,.ui-popup-focus").remove();
    };
    /*保存*/
    var editWeekly=function (week) {
        weekDayAll=$('.weekDay',$el);
        weekTimeAll=$('.weekTime',$el);
        ContentAll=$('.Content',$el);
        longTimeAll=$('.longTime',$el);
        remarksAll=$('.remarks',$el);
        var obj={};
        var objList=[];

        for(var i=0;i<$('.weekTr',$el).length;i++){
            var objWeekly={};
            objWeekly.weekDay=weekDayAll.eq(i).html();
            objWeekly.weekTime=weekTimeAll.eq(i).html();
            objWeekly.weekContent=ContentAll.eq(i).val();
            objWeekly.longTime=Number(longTimeAll.eq(i).val());
            objWeekly.remarks=remarksAll.eq(i).val();
            objList.push(objWeekly);
        }
        if(editOption.id===null){
           obj={
                "status":editOption.status,
                "createPerson":$cookie.get("userId"),
                "weekYear":editOption.weekYear,
                "weekNum":editOption.weekNum,
                "startTime":editOption.startTime,
                "endTime":editOption.endTime,
                "submitter":editOption.submitter,
                "weekContentList":objList

            };
        }else{
             obj={
                "id":getBean.id,
                "status":getBean.status,
                "weekYear":getBean.weekYear,
                "weekNum":getBean.weekNum,
                "startTime":getBean.startTime,
                "endTime":getBean.endTime,
                "excelName":getBean.excelName,
                "excelUrl":getBean.excelUrl,
                "sheetName":getBean.sheetName,
                "submitter":getBean.submitter,
                 "submitterId":getBean.submitterId,
                "createPerson":getBean.createPerson,
                "updatePerson":getBean.updatePerson,
                "weekContentList":objList

            };
        }
        if(editWeeklyValidation.form()){
                Util.ajax.postJson(AjaxPath.weekly+"/week/"+week, JSON.stringify(obj), function(result, isok) {
                    //console.log(result);
                    if (result.returnCode === "0000") {
                        new Dialog({
                            mode: 'tips',
                            delayRmove:1.5, //延迟删除秒数设定 tips默认3秒,非tips默认不关闭。
                            tipsType:'success', //tips类型；可选 success | error，默认普通tips。
                            width:320,
                            height:180,
                            content: '<div style="text-align:center;margin-top:90px">' + result.returnMessage + '</div>'
                        });
                        setTimeout(function () {
                            btnBack();
                        },1500);

                    } else {
                        new Dialog({
                            mode: 'confirm', // 对话框模式，默认normal标准|confirm浮动层|confirm确认对话框
                            title: '提示',
                            width: 300, //对话框宽度，可选项。normal默认值为600，confirm默认值为300，tips默认值为240
                            height: 120, //对话框高度，可选项。normal默认值为400，confirm默认值为180，tips默认值为80
                            cancelDisplay: false, //是否显示取消按钮（强制执行，可在confirm模式下生效），可选项。 默认true(显示)
                            modal: true,
                            content: '<div style="text-align:center;margin-top:50px">' + result.returnMessage + '</div>'// 对话框内容，可以是字符串、html片段、或dom对象,默认为loading状态（点组成的圈）
                        });
                    }



                },"application/json")


        }else{
            console.log("验证失败")
        }

    };
    /*提交*/

    /*获取bean*/
    var getWeekly=function () {
        if(editOption.id===null){
            $(".editWeeklyList", $el).html(Util.hdb.compile(editTable)(editOption));
            //htWeekDays();
            //console.log( htWeekDays());
            var newTime=htWeekDays(editOption.startTime);
            for(var k=0;k<newTime.length;k++){
                //console.log(newTime[k])
                $('.weekTime',$el).eq(k).html(newTime[k]);
            }
            $('.weekStatus',$el).html("&nbsp;未填写");
            $('.weekYear',$el).html(editOption.weekYear+"年&nbsp;");
            $('.weekNum',$el).html("第"+editOption.weekNum+"周&nbsp;");
            $('.weekT',$el).html(new Date(editOption.startTime).Format('yyyy-MM-dd')+" &nbsp;~ &nbsp;"+new Date(editOption.endTime).Format('yyyy-MM-dd '));

        }else{
            Util.ajax.getJson(AjaxPath.weekly + "/week/getWeek/"+editOption.id,{}, function(result, isok) {
                if (result.returnCode === "0000") {
                    getResult=result.beans;
                    getBean=result.bean;
                    for(var i=0; i<getResult.length;i++){
                        getResult[i].createTimeDate = new Date(getResult[i].weekTime).Format('yyyy-MM-dd');
                        //console.log( getResult[i].createTimeDate)
                    }
                    $(".editWeeklyList", $el).html(Util.hdb.compile(editWeeklyTable)(result));
                    //console.log(weekOne)

                    for(var i=0; i<$('.weekTr',$el).length;i++){
                        if(i % 2 == 0) {
                            $('.weekTr',$el).eq(i).addClass("evenTr");
                        }else {
                            $('.weekTr',$el).eq(i).addClass("oddTr");
                        }//否则是奇
                    };

                    for(var i=0; i<$('.longTime',$el).length;i++){
                        $('.longTime',$el).eq(0).attr("name","editWeeklyOne");
                        $('.longTime',$el).eq(1).attr("name","editWeeklyTwo");
                        $('.longTime',$el).eq(2).attr("name","editWeeklyThree");
                        $('.longTime',$el).eq(3).attr("name","editWeeklyFour");
                        $('.longTime',$el).eq(4).attr("name","editWeeklyFive");
                        $('.longTime',$el).eq(5).attr("name","editWeeklySix");
                        $('.longTime',$el).eq(6).attr("name","editWeeklySeven");

                    }
                    var weekStatus="";
                    if(result.bean.status===0){
                        weekStatus="&nbsp;未填写";
                    }else if(result.bean.status===1){
                        weekStatus="&nbsp;已填写，未提交";
                    }else if(result.bean.status===2){
                        weekStatus="&nbsp;已提交";
                    }
                    $('.weekStatus',$el).html(weekStatus);
                    $('.weekYear',$el).html(result.bean.weekYear+"年&nbsp;");
                    $('.weekNum',$el).html("第"+result.bean.weekNum+"周&nbsp;");
                    $('.weekT',$el).html(new Date(result.bean.startTime).Format('yyyy-MM-dd')+" &nbsp;~ &nbsp;"+new Date(result.bean.endTime).Format('yyyy-MM-dd '));

                }
            });
        }


    };
    /*表单验证*/
    var editValidation = function() {
        editWeeklyValidation = new Validator({
            el: $(".editWeeklyForm", $el),
            submitBtn: $(".submitBtn,.saveBtn",$el), //触发验证的按钮，可不配置
            dialog: true, //是否弹出验证结果对话框
            //pattern: { integeNew:"^[1-9]\\d*$"},
            rules: {
                editWeeklyOne: "integeNew",
                editWeeklyTwo: "integeNew",
                editWeeklyThree: "integeNew",
                editWeeklyFour: "integeNew",
                editWeeklyFive: "integeNew",
                editWeeklySix: "integeNew",
                editWeeklySeven: "integeNew"
                //备注

            },
            messages: {
                editWeeklyOne: {
                    integeNew: "仅支持0-24的数字"
                },editWeeklyTwo: {
                    integeNew: "仅支持0-24的数字"
                },editWeeklyThree: {
                    integeNew: "仅支持0-24的数字"
                },editWeeklyFour: {
                    integeNew: "仅支持0-24的数字"
                },editWeeklyFive: {
                    integeNew: "仅支持0-24的数字"
                },editWeeklySix: {
                    integeNew: "仅支持0-24的数字"
                },editWeeklySeven: {
                    integeNew: "仅支持0-24的数字"
                }
            }
        });
        editWeeklyValidation.addMethod("integeNew", function(str) {
            return new RegExp("^(0|0\\.[1-9]|[1-9](\\.\\d)?|1\\d(\\.\\d)?|2[0-3](\\.\\d)?|24)$").test(str);

        });
    };
    return initialize;
});